"""认证中间件"""
from django.shortcuts import redirect
from django.utils.deprecation import MiddlewareMixin
from web import models
from django.conf import settings
import datetime


# 自定义tracer类封装 用户对象和 价格策略对象
class Tracer(object):
    def __init__(self):
        self.user = None
        self.price_policy = None
        self.project = None


class AuthMiddleware(MiddlewareMixin):
    def process_request(self, request):
        # 从session中取登陆过后的用户id
        uid = request.session.get('user_id', 0)
        user_obj = models.UserInfo.objects.filter(id=uid).first()
        # 如果登陆过 则session有值，并设置request 全局参数
        # 实例化 tracer类
        request.tracer = Tracer()
        # 修改Tracer 的user属性
        request.tracer.user = user_obj

        # 实现对用户认证成功之后可以访问的网站 过滤
        # 获取 当前访问的url
        current_url = request.path_info
        # 判断如果 当前url 在 白名单url列表中，则无需登录 也可以访问，反之需要登陆
        if current_url in settings.VALID_URL_LIST:
            return
            # 如果 request.tracer 为None 则需要访问登录界面
        if not request.tracer.user:
            return redirect('login')

        # 登录之后 获取用户所有用的额度，获取最新购买的额度
        _object = models.Transaction.objects.filter(user=user_obj, status=2).order_by('-id').first()
        # 1.判断 额度是否过期，如果过期则使用免费额度
        current_datetime = datetime.datetime.now()
        if _object.end_datetime and _object.end_datetime < current_datetime:
            _object = models.Transaction.objects.filter(user=user_obj, status=2, price_policy__category=1).first()

        # 修改Tracer的price_policy属性值
        request.tracer.price_policy = _object.price_policy

    def process_view(self, request, view_func, view_args, view_kwargs):
        # 判断url 是否是以manage开头
        current_url = request.path_info
        if not current_url.startswith('/manage/'):
            return
        # 判断如果不是用户所创建的项目，或参与的，则返回项目列表界面
        project_id = view_kwargs.get('project_id')
        my_project_obj = models.Project.objects.filter(creator=request.tracer.user, id=project_id).first()
        if my_project_obj:
            request.tracer.project = my_project_obj  # 将项目对象付给全局request属性
            return
        join_project_obj = models.ProjectUser.objects.filter(user=request.tracer.user, project_id=project_id).first()
        if join_project_obj:
            request.tracer.project = join_project_obj.project
            return
        return redirect('project_list')
